<template>
  <div class="login-container">
    <div class="login-card">
      <h2 class="logo">RedBook</h2>
      <div class="form-group">
        <input v-model="username" placeholder="用户名" class="form-input">
      </div>
      <div class="form-group">
        <input v-model="password" type="password" placeholder="密码" class="form-input">
      </div>
      <button @click="login" class="login-btn">登录</button>
      <div class="divider">
        <span>或</span>
      </div>
      <button @click="$router.push('/register')" class="register-btn">注册账号</button>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      username: '',
      password: ''
    }
  },
  methods: {
    async login() {
      try {
        const res = await this.$http.post('/api/login', {
          username: this.username,
          password: this.password
        });
        if (res.data.token) {
          // 保存token和用户信息
          localStorage.setItem('token', res.data.token);
          localStorage.setItem('userId', res.data.userId);
          localStorage.setItem('username', res.data.username);
          // 保存头像信息（无论是否为空）
          localStorage.setItem('avatar', res.data.avatar || '');
          
          console.log('Login successful, avatar:', res.data.avatar);
          
          // 立即触发storage事件通知NavBar更新
          window.dispatchEvent(new Event('storage'));
          
          // 强制刷新页面以确保所有组件重新加载
          setTimeout(() => {
            window.location.href = '/';
          }, 100);
        }
      } catch (error) {
        alert('登录失败: ' + (error.response?.data?.error || '未知错误'));
      }
    }
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f5f5;
}

.login-card {
  background: white;
  padding: 30px;
  border-radius: 10px;
  box-shadow: 0 4px 20px rgba(0,0,0,0.1);
  width: 350px;
  text-align: center;
}

.logo {
  color: #ff2449;
  font-size: 32px;
  margin-bottom: 30px;
}

.form-group {
  margin-bottom: 20px;
}

.form-input {
  width: 100%;
  padding: 12px 15px;
  border: 1px solid #e0e0e0;
  border-radius: 5px;
  font-size: 14px;
}

.login-btn {
  width: 100%;
  padding: 12px;
  background: #ff2449;
  color: white;
  border: none;
  border-radius: 5px;
  font-size: 16px;
  font-weight: bold;
  cursor: pointer;
  margin-bottom: 20px;
}

.divider {
  position: relative;
  margin: 20px 0;
}

.divider span {
  background: white;
  padding: 0 10px;
  position: relative;
  z-index: 1;
  color: #999;
}

.divider::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 0;
  right: 0;
  height: 1px;
  background: #e0e0e0;
}

.register-btn {
  width: 100%;
  padding: 12px;
  background: white;
  color: #ff2449;
  border: 1px solid #ff2449;
  border-radius: 5px;
  font-size: 16px;
  font-weight: bold;
  cursor: pointer;
}
</style>